package com.lmm.lcbusiness.lcbusiness.server;

import android.app.IntentService;
import android.content.Intent;
import android.support.annotation.Nullable;
import com.lmm.dresswisdom.lmmframe.retrofit.AppCallBack;
import com.lmm.dresswisdom.lmmframe.retrofit.AppClient;
import com.lmm.dresswisdom.lmmframe.util.LogUtils;
import com.lmm.lcbusiness.lcbusiness.BaseReturnInfo;
import com.lmm.lcbusiness.lcbusiness.commodel.GoodsCategoryModel;
import com.lmm.lcbusiness.lcbusiness.config.AppInfoAction;
import com.lmm.lcbusiness.lcbusiness.config.ConfigValue;
import com.lmm.lcbusiness.lcbusiness.config.DataSafeUtil;
import com.lmm.lcbusiness.lcbusiness.dbmodel.AttrRealm;
import com.lmm.lcbusiness.lcbusiness.dbmodel.CategoryAttr_Relation_Realm;
import com.lmm.lcbusiness.lcbusiness.dbmodel.GoodsCategoryRealm;
import com.lmm.lcbusiness.lcbusiness.dbmodel.ItemRealm;
import com.lmm.lcbusiness.lcbusiness.server.model.AttrModel;
import com.lmm.lcbusiness.lcbusiness.server.model.CategoryAttr_Relation_Model;
import com.lmm.lcbusiness.lcbusiness.server.model.ItemModel;
import com.lmm.lcbusiness.lcbusiness.utils.RealmUtils;

import java.util.List;
import java.util.Map;

import io.realm.Realm;

/**
 * @author xmgong
 * @date 2017/12/1
 * 后台更新服务
 */
public class UpdateIntentService extends IntentService {
    private final String TAG = "UpdateIntentService";
    private UpdateAction mAction;

    public UpdateIntentService() {
        super("UpdateIntentService");
        mAction = AppClient.getRetrofit(ConfigValue.apiUrl).create(UpdateAction.class);
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        updateCategoryAction();
    }

    /**
     * 更新栏目
     */
    private void updateCategoryAction() {
        Map<String, String> params = AppInfoAction.getParams();
        AppClient.request(mAction.getGoodsCategoryAction(DataSafeUtil.EncodeMAP(params)), new AppCallBack<BaseReturnInfo<List<GoodsCategoryModel>>>() {
            @Override
            public void onSuccess(BaseReturnInfo<List<GoodsCategoryModel>> returnInfo) {
                if (returnInfo.isSuccess()) {
                    saveCategory(returnInfo.getData());
                }
            }

            @Override
            public void onFailure(String s) {
                LogUtils.write(s);
            }

            @Override
            public void onFinish() {
                updateAttributeTable();
            }
        });
    }

    /**
     * 更新所有商品类别和属性的关系
     */
    private void updateAttributeTable() {
        Map<String, String> params = AppInfoAction.getParams();
        AppClient.request(mAction.getAttributeTable(DataSafeUtil.EncodeMAP(params)), new AppCallBack<BaseReturnInfo<List<CategoryAttr_Relation_Model>>>() {
            @Override
            public void onSuccess(BaseReturnInfo<List<CategoryAttr_Relation_Model>> returnInfo) {
                if (returnInfo.isSuccess()) {
                    List<CategoryAttr_Relation_Model> mdata = returnInfo.getData();
                    saveCategoryRelation(mdata);
                }
            }

            @Override
            public void onFailure(String s) {
                LogUtils.write(s);
            }

            @Override
            public void onFinish() {
                updateAttribute();
            }
        });
    }

    /**
     * 更新所有商品属性
     */
    private void updateAttribute() {
        Map<String, String> params = AppInfoAction.getParams();
        AppClient.request(mAction.getGoodsAttribute(DataSafeUtil.EncodeMAP(params)), new AppCallBack<BaseReturnInfo<List<AttrModel>>>() {
            @Override
            public void onSuccess(BaseReturnInfo<List<AttrModel>> returnInfo) {
                if (returnInfo.isSuccess()) {
                    saveAttribute(returnInfo.getData());
                }
            }

            @Override
            public void onFailure(String s) {
                LogUtils.write(s);
            }

            @Override
            public void onFinish() {
                updateItemList();
            }
        });
    }

    /**
     * 获取所有枚举
     */
    private void updateItemList() {
        Map<String, String> params = AppInfoAction.getParams();
        AppClient.request(mAction.getItemListAll(DataSafeUtil.EncodeMAP(params)), new AppCallBack<BaseReturnInfo<List<ItemModel>>>() {
            @Override
            public void onSuccess(BaseReturnInfo<List<ItemModel>> returnInfo) {
                if (returnInfo.isSuccess()) {
                    saveItemList(returnInfo.getData());
                }
            }

            @Override
            public void onFailure(String s) {

            }

            @Override
            public void onFinish() {

            }
        });
    }


    /**
     * 保存商品属性关系
     *
     * @param mdata
     */
    private void saveCategoryRelation(List<CategoryAttr_Relation_Model> mdata) {
        Realm realm = RealmUtils.getRealm();
        realm.beginTransaction();
        realm.delete(CategoryAttr_Relation_Realm.class);
        CategoryAttr_Relation_Realm item = null;
        for (CategoryAttr_Relation_Model crm : mdata) {
            item = realm.createObject(CategoryAttr_Relation_Realm.class);
            item.setAttrId(crm.getAttrId());
            item.setCatId(crm.getCatId());
            item.setId(crm.getId());
            item.setSortNo(crm.getSortNo());
            realm.copyFromRealm(item);
        }
        realm.commitTransaction();
    }

    /**
     * 保存属性
     */
    private void saveAttribute(List<AttrModel> mdata) {
        Realm realm = RealmUtils.getRealm();
        realm.beginTransaction();
        realm.delete(AttrRealm.class);
        AttrRealm item = null;
        for (AttrModel am : mdata) {
            item = realm.createObject(AttrRealm.class);
            item.setAttrId(am.getAttrId());
            item.setAttrName(am.getAttrName());
            item.setCategoryId(am.getCategoryId());
            item.setDicId(am.getDicId());
            item.setInputType(am.getInputType());
            item.setIsDefault(am.getIsDefault());
            item.setIsMain(am.getIsMain());
            item.setIsMust(am.getIsMust());
            item.setIsNormal(am.getIsNormal());
            item.setSort(am.getSort());
            item.setSortNo(am.getSortNo());
            item.setValueType(am.getValueType());
            realm.copyFromRealm(item);
        }
        realm.commitTransaction();
    }

    /**
     * 保存枚举数据字典
     *
     * @param mdata
     */
    private void saveItemList(List<ItemModel> mdata) {
        Realm realm = RealmUtils.getRealm();
        realm.beginTransaction();
        realm.delete(ItemRealm.class);
        ItemRealm item = null;
        for (ItemModel im : mdata) {
            item = realm.createObject(ItemRealm.class);
            item.setDicId(im.getDicId());
            item.setId(im.getId());
            item.setItemValue(im.getItemValue());
            item.setSortNo(im.getSortNo());
            realm.copyFromRealm(item);
        }
        realm.commitTransaction();
    }


    /**
     * 保存栏目
     *
     * @param categoryRealmList
     */
    private void saveCategory(List<GoodsCategoryModel> categoryRealmList) {
        Realm realm = RealmUtils.getRealm();
        realm.beginTransaction();
        realm.delete(GoodsCategoryRealm.class);
        GoodsCategoryRealm item = null;
        for (GoodsCategoryModel gcgm : categoryRealmList) {
            item = realm.createObject(GoodsCategoryRealm.class);
            item.setCatCode(gcgm.getCatCode());
            item.setCatId(gcgm.getCatId());
            item.setCatIndex(gcgm.getCatIndex());
            item.setCatName(gcgm.getCatName());
            item.setEnable(gcgm.getEnable());
            item.setSort(gcgm.getSort());
            item.setIsType(gcgm.getIsType());
            item.setParentId(gcgm.getParentId());
            realm.copyFromRealm(item);
        }
        realm.commitTransaction();
    }

}
